<?php
/**
 * Created by PhpStorm.
 * User: Administratorjing
 * Date: 2018/7/23/023
 * Time: 23:30
 * By Hedy<714195347@qq.com>
 */

namespace App\Http\Controllers;


use App\Http\Requests\AddCartRequest;
use App\Http\Requests\Request;
use App\Models\CartItem;
use App\Models\ProductSku;
use App\Services\CartService;

class CartController extends Controller
{
    //引入封装类
    protected $cartService;
    //注入cartService类
    public function __construct(CartService $cartService)
    {
        $this->cartService = $cartService;
    }

    /**
     * 购物车的展示
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        //取出购物车的数据
        //with(['productSku.product']) 方法用来预加载购物车里的商品和 SKU 信息
        //Laravel 还支持通过 . 的方式加载多层级的关联关系
//        $cartItems = $request->user()->cartItems()->with(['productSku.product'])->get();
        $cartItems = $this->cartService->get();
        $addresses = $request->user()->addresses()->orderBy('last_used_at','desc')->get();
        //dd($addresses);
        return view('cart.index',[
            'cartItems'=>$cartItems,
            'addresses'=>$addresses
        ]);
    }

    /**
     * 添加购物车
     * @param AddCartRequest $request
     * @return array
     */
   public function add(AddCartRequest $request)
   {
       //获取数据
//       $user = $request->user();
//       $skuId = $request->input('sku_id');
//       $amount = $request->input('amount');
//       //从数据库中查询该商品是否存在购物车中
//       if($cart = $user->cartItems()->where('product_sku_id',$skuId)->first()){
//           //如果存在则直接叠加商品数量
//           $cart->update([
//               'amount'=>$cart->amount+$amount,
//           ]);
//       }else{
//           //创建一个新的购物车记录
//           $cart = new CartItem(['amount'=>$amount]);
//           $cart->user()->associate($user);
//           $cart->productSku()->associate($skuId);
//           $cart->save();
//       }
       $this->cartService->add($request->input('sku_id'),$request->input('amount'));
       return [];
   }

   public function remove(ProductSku $sku,Request $request)
   {
//       $request->user()->cartItems()->where('product_sku_id',$sku->id)->delete();
//       return;
       $this->cartService->remove($sku->id);
       return [];
   }
}